﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web.Security;
using log4net;
using RIBA.Web.Model;

namespace RIBA.Web.Services
{
	public class CustomRoleProvider : RoleProvider
	{
		private static readonly ILog _log = LogManager.GetLogger(typeof(CustomRoleProvider));

		public override string[] GetRolesForUser(string username)
		{
			try
			{
				_log.DebugFormat("GetRolesForUser: username='{0}'", username);

				ObjectCache cache = MemoryCache.Default;
				var item = cache.GetCacheItem(username);

				if (item != null)
				{
					var list = item.Value as IList<string>;
					return list.ToArray();
				}

				var entities = new UserEntitiesMock();
				var autUser = entities.Users.SingleOrDefault(e => e.Name == username);
				cache.Add(username, autUser.Roles, new DateTimeOffset(DateTime.Now.AddMinutes(5)), null);

				return autUser.Roles.ToArray();
			}
			catch (Exception ex)
			{
				_log.Fatal(string.Format("Error in GetRolesForUser. username='{0}'", username), ex);
				return null;
			}
		}

		public override string ApplicationName
		{
			get { return "RIBA"; }
			set { throw new NotImplementedException(); }
		}

		public override void AddUsersToRoles(string[] usernames, string[] roleNames)
		{
			throw new NotImplementedException();
		}

		public override void CreateRole(string roleName)
		{
			throw new NotImplementedException();
		}

		public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
		{
			throw new NotImplementedException();
		}

		public override string[] FindUsersInRole(string roleName, string usernameToMatch)
		{
			throw new NotImplementedException();
		}

		public override string[] GetAllRoles()
		{
			throw new NotImplementedException();
		}

		public override string[] GetUsersInRole(string roleName)
		{
			throw new NotImplementedException();
		}

		public override bool IsUserInRole(string username, string roleName)
		{
			throw new NotImplementedException();
		}

		public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
		{
			throw new NotImplementedException();
		}

		public override bool RoleExists(string roleName)
		{
			throw new NotImplementedException();
		}
	}
}